package com.wuhuahe.learning.lagou.cloud.gateway.filters;

import com.wuhuahe.learning.lagou.servie.feign.api.UserFeignApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {


    @Autowired
    private UserFeignApi userFeignApi;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        URI uri = request.getURI();
        String path = uri.getPath();
        ServerHttpRequest.Builder mutate = request.mutate();
        if(path.startsWith("/api/user/") || path.startsWith("/api/code")){
            ServerHttpRequest buildReuqest = mutate.build();
            return chain.filter(exchange.mutate().request(buildReuqest).build());
        }

        String token = "";
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        Loop:
        for (Map.Entry<String, List<HttpCookie>> entry : cookies.entrySet()) {
            List<HttpCookie> httpCookies = entry.getValue();
            for (HttpCookie httpCookie : httpCookies) {
                if (httpCookie.getName().equals("sessionId")) {
                    token = httpCookie.getValue();
                    break Loop;
                }
            }

        }
        if("".equals(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer wrap = response.bufferFactory().wrap("UnAuthorized".getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        String email = userFeignApi.info(token);

        if (email != null && !"".equals(email)) {
            ServerHttpRequest buildReuqest = mutate.build();
            return chain.filter(exchange.mutate().request(buildReuqest).build());
        } else {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer wrap = response.bufferFactory().wrap("UnAuthorized".getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}